package com.rhb.cg;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;

import java.io.*;
import java.util.*;

public class CodeGeneratorTask extends Task {
	private File xml;    
	private File xmldir;    
	private String xmlfile; 

	private File vmdir;	
	private List<String> vmlist = new ArrayList<String>(); 
	   
	protected Vector<FileSet> filesets = new Vector<FileSet>();

	private File output;
	private File report;

	public void execute() throws BuildException {
		if(output==null) output = getProject().getBaseDir();
		if(report==null) report = getProject().getBaseDir();
	    refreshVmlist();
		
		CodeGenerator code = new CodeGenerator();
		System.out.println(code.generate(vmlist,getXml().getPath(),vmdir.getPath(),output.getPath(),report.getPath()));
	}

	private void refreshVmlist(){
		vmlist.clear();
		for(Object fs:filesets){
			if(vmlist.size()>0) break;
			
			FileSet set = (FileSet)fs;
			DirectoryScanner ds = null;
			try {
				ds = set.getDirectoryScanner(getProject());
			} catch (BuildException e){}
			
			vmdir = set.getDir(getProject());
			String[] files = ds.getIncludedFiles();
			for (String file:files){                    
				File vm = new File(vmdir,file);
				vmlist.add(vm.getName());
			}
		}
	}
	
	public File getXml() {
		if(xml!=null) return xml;
		else{
			if(xmldir==null) xmldir = getProject().getBaseDir();
			File xm = new File(xmldir,xmlfile);
			return xm;
		}
	}
	public void setXml(File xml) {
		this.xmldir = null;
		this.xmlfile = null;
		this.xml = xml;
	}
	public void setXmldir(File xmldir) {
		if(xml==null)
			this.xmldir = xmldir; 
	}
	public void setXmlfile(String xmlfile) {
		if(xml==null)
			this.xmlfile = xmlfile;
	}
	
	public void addFileset(FileSet set){
		filesets.addElement(set);
	}

	public void setOutput(File op) {
		this.output = op;
	}
	public void setReport(File rt) {
		this.report = rt;
	}
}

